package com.voja.mrvica2;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import android.graphics.Bitmap;
import android.util.LruCache;

public class Cache {

	private int max_size = 1024 * 1024 * 50;  // 50MB
	
	private LruCache<String, Object> _lru;
	private HashMap<String, Date> created;
	private int lifetime;
	
	public Cache(int maxSize) {
		this(maxSize, 60 * 60 *24);  // for 1 day
	}
	
	public Cache(int maxSize, int lifetime) {
		max_size      = maxSize;
		_lru          = new LruCache<String, Object>(max_size);
		created       = new HashMap<String, Date>();
		this.lifetime = lifetime;
	}
	
	public Bitmap getBitmap(String key) {
		Object val = get(key);
		return (Bitmap)val;
	}
	public void setBitmap(String key, Bitmap value) {
		Object val = (Object)value;
		set(key, val);
	}
	
	
	public Object get(String key) {
		Object ret=null;
		
		try {
			boolean expired = true;
			Date now  = getDate();
			Date date = created.get(key);
			
			if (date != null) {
				long n = now.getTime();
				long d = date.getTime();
				
				if ((n-d) <= lifetime) {
					expired = false;
				}
			}
			
			if (! expired) {
				ret = _lru.get(key);
			}
		} catch (Exception e) {
			// do nothing, return null
			ret = null;
		}
		
		return ret;
	}
	public void set(String key, Object value) {
		try {
			_lru.put(key, value);
			created.put(key, getDate());
		} catch (Exception e) {
			// do nothing
		}
	}
	
	private Date getDate() {
		return Calendar.getInstance().getTime();
	}

}
